const Announcement = require('../models/Announcement');
const User = require('../models/User');

// 创建公告
exports.createAnnouncement = async (req, res) => {
  try {
    const { title, content } = req.body;
    const announcement = await Announcement.create({
      title,
      content,
      createdBy: req.user.id
    });

    res.status(201).json({
      success: true,
      data: announcement
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建公告失败',
      error: error.message
    });
  }
};

// 获取所有公告
exports.getAllAnnouncements = async (req, res) => {
  try {
    const announcements = await Announcement.findAll({
      order: [['createdAt', 'DESC']],
      include: [{ model: User, as: 'creator', attributes: ['id', 'name', 'email'] }]
    });

    res.status(200).json({
      success: true,
      data: announcements
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取公告列表失败',
      error: error.message
    });
  }
};

// 获取单个公告
exports.getAnnouncementById = async (req, res) => {
  try {
    const { id } = req.params;
    const announcement = await Announcement.findByPk(id,
      { include: [{ model: User, as: 'creator', attributes: ['id', 'name', 'email'] }]
    });

    if (!announcement) {
      return res.status(404).json({
        success: false,
        message: '公告不存在'
      });
    }

    res.status(200).json({
      success: true,
      data: announcement
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取公告详情失败',
      error: error.message
    });
  }
};

// 更新公告
exports.updateAnnouncement = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content, isActive } = req.body;

    const announcement = await Announcement.findByPk(id);
    if (!announcement) {
      return res.status(404).json({
        success: false,
        message: '公告不存在'
      });
    }

    await announcement.update({
      title: title || announcement.title,
      content: content || announcement.content,
      isActive: isActive !== undefined ? isActive : announcement.isActive
    });

    res.status(200).json({
      success: true,
      message: '公告更新成功',
      data: announcement
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新公告失败',
      error: error.message
    });
  }
};

// 删除公告
exports.deleteAnnouncement = async (req, res) => {
  try {
    const { id } = req.params;
    const announcement = await Announcement.findByPk(id);

    if (!announcement) {
      return res.status(404).json({
        success: false,
        message: '公告不存在'
      });
    }

    await announcement.destroy();
    res.status(200).json({
      success: true,
      message: '公告删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除公告失败',
      error: error.message
    });
  }
};